package cn.edu.zafu.bigdata.x.hjn;

import java.io.*;
import java.net.*;

public class TCPClient {
    public static void main(String[] args) {
        try {
            // 连接到服务端（替换为服务端的IP和端口）
            Socket socket = new Socket("localhost", 12345);
            System.out.println("已连接到服务器...");

            // 获取输入输出流
            BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String message;
            while (true) {
                System.out.print("请输入消息：");
                message = userInput.readLine();  // 从用户输入读取消息
                if (message.equalsIgnoreCase("exit")) {
                    break;  // 输入exit退出聊天
                }

                // 发送消息到服务端
                out.println(message);

                // 接收并输出服务端的回复
                String response = in.readLine();
                System.out.println(response);
            }

            // 关闭资源
            userInput.close();
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
